import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';

const request = axios.create({
    baseURL: '/api',
    timeout: 10000,
    withCredentials: true
});

// 请求拦截器
request.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        console.log('发送请求前的token:', token);
        
        if (token) {
            // 尝试不同的token格式
            // config.headers['Authorization'] = `Bearer ${token}`;
            config.headers['Authorization'] = token;
            
            // 打印完整的请求配置
            console.log('完整的请求配置:', {
                url: config.url,
                method: config.method,
                headers: config.headers,
                data: config.data
            });
        } else {
            console.warn('未找到token');
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        console.log('请求成功，响应数据:', response.data);
        return response.data;
    },
    error => {
        console.error('请求失败:', error.response || error);
        
        if (error.response?.status === 401) {
            console.log('401错误详情:', {
                url: error.config.url,
                headers: error.config.headers,
                token: localStorage.getItem('token')
            });
            
            ElMessage.error('请先登录或登录已过期');
            localStorage.removeItem('token');
            router.push('/login');
        } else {
            ElMessage.error(error.response?.data?.message || '请求失败');
        }
        return Promise.reject(error);
    }
);

export default request; 